package com.example.train_operate.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Random;

public class RandomUtil {

    /**
     * 生成16位随机字符串
     * @param charSet
     * @param random
     * @return
     */
    public static String generateRandomString(String charSet, Random random){
        StringBuilder sb = new StringBuilder(16);
        for(int i = 0; i < 16; i++){
            int index = random.nextInt(charSet.length());
            sb.append(charSet.charAt(index));
        }
        return sb.toString();
    }

    public static String getCheckSum(String appSecret, String nonce){
        long curTime = System.currentTimeMillis() / 1000;
        return shal(appSecret + nonce + curTime);
    }

    private static String shal(String input) {
        try{
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            byte[] result = messageDigest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for(byte b : result){
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e){
            throw new RuntimeException("SHAL哈希计算错误！");
        }
    }
}
